<?

require(dirname(__FILE__).'/_base/BaseUsers.php');

class Users extends BaseUsers
{
    
    public $avatar_old;
    public $passwordApp;
    public $verifyCode;
    
    public $adminName='Пользователи';
    public $pluralNames=array('Пользователя');
    public $_roleChoices = array();
    
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }
    
    function getRoleChoices(){
        if(empty($this->_roleChoices)){
            $_roles = include(dirname(__FILE__).'/../data/roles.php');
            foreach($_roles as $k=>$r){
                if($k == 'guest') continue;
                $this->_roleChoices[$k] = $r['description'];
            }
        }
        return $this->_roleChoices;
    }
    
    public function rules(){
        return array(
            // all
            array('email, role', 'required'),
            array('cost_dev, cost_support', 'numerical'),
            array('active, time_reg, time_lastlogin', 'numerical', 'integerOnly'=>true),
            array('avatar', 'length', 'max'=>255),
            array('nick, name, lname, email', 'length', 'max'=>60),
            array('password, checkword', 'length', 'max'=>32),
            array('role', 'length', 'max'=>20),
            array('time_reg', 'default', 'setOnEmpty' => true, 'value' => time()),
            array('cost_dev, cost_support', 'default', 'setOnEmpty' => true, 'value' => null),
            array('email', 'unique', 'message'=>Yii::t('errors', 'Form value already exists')),
            
            // on insert
            array('email', 'email', 'message'=>'Неверный формат E-mail', 'on'=>'insert'),
            
            // on registration
            array('name, lname, password, passwordApp, verifyCode', 'required', 'on'=>'registration'),
            array('password', 'compare', 'compareAttribute' => 'passwordApp', 'on'=>'registration'),
            array('verifyCode', 'captcha', 'allowEmpty' => !extension_loaded('gd'), 'captchaAction' => 'site/captcha', 'on'=>'registration'),
            array('role', 'default', 'setOnEmpty' => true, 'value' => 'user', 'on'=>'registration'),
            
            // on search
            array('id, active, role, nick, name, lname, email, password, time_reg, time_lastlogin, checkword, avatar, cost_dev, cost_support',
                'safe', 'on'=>'search'
            ),
        );
    }
    
    public function relations() {
        return array(
            'projects' => array(self::MANY_MANY, 'TaskProjectUser', 'user_id')
        );
    }
    
    public function attributeLabels(){
        return array(
            'id' => UserModule::t('fields', 'ID'),
            'active' => UserModule::t('fields', 'Активирован'),
            'nick' => UserModule::t('fields', 'Ник'),
            'name' => UserModule::t('fields', 'Имя'),
            'lname' => UserModule::t('fields', 'Фамилия'),
            'email' => UserModule::t('fields', 'Email'),
            'password' => UserModule::t('fields', 'Пароль'),
            'passwordApp' => UserModule::t('fields', 'Подтверждение пароля'),
            'verifyCode' => UserModule::t('fields', 'Буквы с картинки'),
            'time_reg' => UserModule::t('fields', 'Дата регистрации'),
            'time_lastlogin' => UserModule::t('fields', 'Дата последнего входа'),
            'checkword' => UserModule::t('fields', 'Контрольная строка'),
            'avatar' => UserModule::t('fields', 'Аватар'),
            'role' => UserModule::t('fields', 'Роль'),
            'cost_dev' => UserModule::t('fields', 'Стоимость часа разработок'),
            'cost_support' => UserModule::t('fields', 'Стоимость часа техподдержки'),
        );
    }
    
    static function CryptPassword($password){
        return md5(PASSWORD_SECRET1.$password.PASSWORD_SECRET2);
    }
    
    public function uploadAvatar($save=false){
        $file = $this->avatar;
        if(!empty($file)){
            $hash = md5(time().rand());
            $ext = CFileHelper::getExtension($file->name);
            $path = '/upload/avatars/'.substr($hash,0,3);
            $_path = $_SERVER['DOCUMENT_ROOT'].$path;
            $_file = $_path.'/'.$hash.'.'.$ext;
            mkdir($_path, 0777, true); chmod($_path, 0777);
            $file->saveAs($_file);
            chmod($_file, 0777);
            SimpleImage::resizeAndCrop($_file, $_file, 24);
            if(!empty($this->avatar_old)){
                $this->deleteAvatar();
            }
            $this->avatar = $path.'/'.$hash.'.'.$ext;
            if($save) $this->save();
        }
    }
    public function deleteAvatar($save=false){
        if(!empty($this->avatar_old) && file_exists($_SERVER['DOCUMENT_ROOT'].$this->avatar_old)){
            unlink($_SERVER['DOCUMENT_ROOT'].$this->avatar_old);
            rmdir(dirname($_SERVER['DOCUMENT_ROOT'].$this->avatar_old));
            $this->avatar_old = '';
            if($save) $this->save();
        }
    }
    
    public function beforeSave(){
        $this->uploadAvatar();
        return true;
    }
    
    public function attributeWidgets(){
        return array(
            array('time_reg','calendar', 'language'=>'ru','options'=>array('dateFormat'=>'yy-mm-dd')),
            array('active','boolean'),
            array('time_reg','timestamp-show'),
            array('password','password','crypt'=>'/user/backendhelper/passwordcrypt'),
            array('role','dropDownList'),
            array('avatar','file-path','method'=>'uploadAvatar'),
        );
    }
    public function adminSearch(){
        return array(
            'columns'=>array(
                'id',
                array(
                    'name'=>'active',
                    'value'=>'$data->active==1 ? CHtml::encode("Да") : CHtml::encode("Нет")',
                    'filter'=>array(1=>'Да',0=>'Нет'),
                ),
                array(
                    'name'=>'role',
                    'value'=>'Users::model()->roleChoices[$data->role]',
                    'filter'=>$this->roleChoices
                ),
                'nick',
                'name',
                'lname',
                'email',
            ),
        );
    }
    
    public function adminUpdateFormIgnoreValues(){
        return array(
            'time_lastlogin', 'verifyCode', 'passwordApp', 'checkword'
        );
    }
    
    public function GetHelpMessage($attr){
        $mes = array(
            'password' => 'Сейчас пароль закодирован шифром md5. Введите новый пароль, он автоматически зашифруется.'
        );
        return $mes[$attr];
    }
    
}
